<template>
  <div class="console-box arcgis_page">
    <div id="map-container"></div>
		<div class="info_container">
			<div class="info_item">经度：<span class="info_text">{{infoData.longitude}}</span></div>
			<div class="info_item">纬度<span class="info_text">{{infoData.latitude}}</span></div>
			<el-button size="mini" @click="addRoad('1')">显示路线</el-button>
			<el-button size="mini" @click="addArrRoad('2')">数组加载</el-button>
			<el-button size="mini" @click="addOneLine('3')">整段铁路</el-button>
		</div>
  </div>
</template>
<script setup>
import { reactive } from 'vue'
import { roadData, initIcon, iconData, roadTextPoints } from './config.js'
import roadDataArr from './data.js'
import railwayData from './railwayData.js'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import Polyline from '@arcgis/core/geometry/Polyline.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'

/** 地图主题 */
let mapView = null
let map = null
let roadGraphicsLayers = null
let imgGraphicsLayers = null

// 已加载的图形
let loadedGraphics = {}

/** 右下角信息 */
const infoData = reactive({
  longitude: 113.23153746586328,
  latitude: 21.938416691169422,
})

/** 载入地图 */
const initMap = () => {
	map = new Map({
		basemap: 'satellite'
	})
	roadGraphicsLayers = new GraphicsLayer() // 创建一个路网图层对象，用于后续添加路线图
	map.add(roadGraphicsLayers) // 将图层添加到地图中

	imgGraphicsLayers = new GraphicsLayer() // 创建一个图层对象，用于后续添加图片
	map.add(imgGraphicsLayers) // 将图层添加到地图中

	// 站如地点标识图标
	iconData.forEach(item => {
		initIcon(imgGraphicsLayers, item)
	})

	mapView = new MapView({
		map: map,
		zoom: 13,
		container: 'map-container',
		center: [113.23153746586328, 21.938416691169422], // 设置地图中心点   [经度，纬度]
	})
	// 移除底部的版权信息
  	mapView.ui.remove("attribution")

	/** 地图点击事件 */
	mapView.on('click', handleMapClick)

	/** 鼠标移动获取经纬度 */
	mapView.on("pointer-move", event => { //监听pointer-move事件
		const point = mapView.toMap({x: event.x,y: event.y}) //将鼠标的像素位置转为经纬度
		infoData.longitude = point.longitude
		infoData.latitude = point.latitude
	})
}
// 大桥的两点坐标，用于计算文字摆放的角度
const addRoad = (id) => {
	if(loadedGraphics[id]) {
		removeRoad(id)
		return
	}
	// 轨迹图形
	const polyline = new Polyline({
		paths: roadData, // paths:[[x1, y1], [x2, y2], ...], spatialReference: new SpatialReference({wkid: xxxx})
		// spatialReference: mapView.spatialReference
	})
	console.log("🚀 ~ addRoad ~ polyline:", polyline)
	// 轨迹图形的的填充1 黄虚线
	const lineGraphic = new Graphic({
		geometry: polyline,
		// symbol: lineSymbol3D,
		symbol: {
			type: "simple-line",
			color: [255, 255, 255], // 白色虚线
			style: "dash",
			cap: "butt",
			width: 1
		}
	})
	// 轨迹图形的的填充2 道路绿实线
	const lineGraphic2 = new Graphic({
		geometry: polyline,
		// symbol: lineSymbol3D,
		symbol: {
			type: "simple-line",
			color: [51, 60, 80],
			cap: "butt",
			width: 8
		}
	})
	// 图层添加到图层组对象
	roadGraphicsLayers.add(lineGraphic2)
	roadGraphicsLayers.add(lineGraphic)
	
	// 生成道路名称的图形
	const graphicObj = generateTextGraphic(id, '黄茅海大桥')
	
	roadGraphicsLayers.add(graphicObj.textGraphic);
	// 图层添加到图层组对象, 用于后续清除
	loadedGraphics[id] = [lineGraphic, lineGraphic2, graphicObj.textGraphic]
	// 将地图视图移动到图形的中心点
	goCenter(graphicObj.centerPoint, 12)
}

const addArrRoad = (id) => {
	if(loadedGraphics[id]) {
		removeRoad(id)
		return
	}
	loadedGraphics[id] =[]
	let _data = roadDataArr
	_data.forEach(item => {
		const polyline = new Polyline({
			paths: item.geometry.paths[0], // paths:[[x1, y1], [x2, y2], ...], spatialReference: new SpatialReference({wkid: xxxx})
		})
		const lineGraphic = new Graphic({
		geometry: polyline,
			symbol: {
				type: "simple-line",
				// color: [252, 167, 34], // 黄色虚线
				color: [255, 255, 255], // 白色虚线
				style: "dash",
				cap: "butt",
				width: 5
			}
		})

		const lineGraphic2 = new Graphic({
			geometry: polyline,
			symbol: {
				type: "simple-line",
				// color: [48, 210, 104],
				color: [51, 60, 80],
				cap: "butt",
				width: 5
			}
		})
		
		loadedGraphics[id].push(lineGraphic, lineGraphic2)
		roadGraphicsLayers.add(lineGraphic2)
		roadGraphicsLayers.add(lineGraphic)
	})
	// 生成道路名称的图形
	const graphicObj = generateTextGraphic(id, '金海大桥')
	loadedGraphics[id].push(graphicObj.textGraphic)
	roadGraphicsLayers.add(graphicObj.textGraphic)
	goCenter(graphicObj.centerPoint, 12)
}


const addOneLine = (id) => {
	if(loadedGraphics[id]) {
		removeRoad(id)
		return
	}
	loadedGraphics[id] = []
	// 南北走向的铁路根据维度数据排序
	let arr = [];
	railwayData.forEach(item => {
		arr = arr.concat(item.geometry.paths[0])
	})
	arr.sort((a, b) => a[1] - b[1])
	// 轨迹图形
	const polyline = new Polyline({
		paths: arr,
	})
	// 轨迹图形的的填充1
	const lineGraphic = new Graphic({
		geometry: polyline,
		symbol: {
			type: "simple-line",
			color: [255, 255, 255],
			style: "dash",
			cap: "butt",
			width: 6
		}
	})
	// 轨迹图形的的填充2
	const lineGraphic2 = new Graphic({
		geometry: polyline,
		symbol: {
			type: "simple-line",
			color: [51, 60, 80],
			cap: "butt",
			width: 6
		}
	})
	// 图层添加到图层组对象
	roadGraphicsLayers.add(lineGraphic2)
	roadGraphicsLayers.add(lineGraphic)
	loadedGraphics[id].push(lineGraphic, lineGraphic2)
	// 生成道路名称的图形
	const graphicObj = generateTextGraphic(id, '广珠铁路')
	loadedGraphics[id].push(graphicObj.textGraphic)
	roadGraphicsLayers.add(graphicObj.textGraphic)
	goCenter(graphicObj.centerPoint, 12)
}

/** 生成道路文字图形 */
const generateTextGraphic = (id, text) => {
	// 画出大桥两点轨迹
	const brigeLine = new Polyline({
		paths: roadTextPoints[id]
	})
	// 选择 Polyline 上的两个点
	const point1 = roadTextPoints[id][0];
	const point2 = roadTextPoints[id][1];
	// 计算倾斜度（单位：度）
	const slope = Math.atan2(point2[1] - point1[1], point2[0] - point1[0]) * 180 / Math.PI;

	const centerpoint = [brigeLine.extent.center.longitude, brigeLine.extent.center.latitude];
	// 在中心点摆放道路文字
	const textPoint = {  
		type: "point",  
		x: centerpoint[0],  
		y: centerpoint[1],  
  }; 
	// 文字
	const textSymbol = {
		type: "text",  // autocasts as new TextSymbol()
		color: [232, 142, 64], // 文字颜色
		haloColor: "black", // 文字光晕颜色
		haloSize: "1px", // 文字光晕大小
		text: text,
		xoffset: -2, //水平偏移量
		yoffset: -2, //垂直偏移量
		angle: -slope, // 倾斜度
		font: { // 文字样式设置
			size: 10,
			weight: "bold"
		}
	}
	//创建文本图形
  const graphicText = new Graphic({
    geometry: textPoint,  
    symbol: textSymbol,
  });	
	return {
		textGraphic: graphicText,
		centerPoint: centerpoint
	}
}

// 移除图形
const removeRoad = (id) => {
	if(!loadedGraphics[id]) return
	loadedGraphics[id].forEach(item => {
		roadGraphicsLayers.remove(item)
	})
	delete loadedGraphics[id]
}

// 前往图形中心点
const goCenter = (center, zoom=12) => {
	mapView.goTo({
		center: center,
		zoom: zoom
	}, 
	{
		// 指是否需要过度动画， 一般都会是true 默认也是true
		animate: true,
		// 动画速度系数 1就是正常速度  0.5就是一半速度 2就是一倍速度
		speedFactor: 1,
		// 持续速度  持续5秒达到  这个配置会覆盖上面的动画系数
		duration: 500,
		// 允许的最大持续时间， 有时候镜头移动距离太远了 如果设置的恒定速度 就会导致时间过长， 这个配置可以解决这个问题
		maxDuration: 1000,
		// 移动的模式  均速移动 还有很多配置 详情见api
		easing: 'linear',
	})
}

const handleMapClick = (event) => {
	const { mapPoint } = event
	console.log("🚀 ~ handleMapClick ~ mapPoint:", mapPoint)
	// infoData.longitude = mapPoint.longitude
	// infoData.latitude = mapPoint.latitude
}


onMounted(() => {
	initMap()
})
</script>
<style scoped lang="scss">
  .arcgis_page {
		position: relative;
    width: 100%;
    height: calc(100vh - 135px);
    padding: 4px;

    #map-container {
      width: 100%;
      height: 100%;
    }

		.info_container {
			position: absolute;
			right: 4px;
			bottom: 4px;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			width: calc(100% - 8px);
			padding: 4px;
			background: #707070;

			.info_item {
				margin-right: 12px;
				color: #fff;

				.info_text {
					display: inline-block;
					width: 172px;
				}
			}
		}
  }
</style>
